package com.cxw.healthserver.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.cxw.healthserver.constant.Constants
import com.cxw.healthserver.entity.Token
import com.cxw.healthserver.mapper.TokenMapper
import com.cxw.healthserver.response.BaseResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TokenService {
    @Autowired
    private lateinit var tokenMapper: TokenMapper
    fun getTokenByUserId(userId: String): Token? {
        return tokenMapper.selectOne(QueryWrapper<Token>().eq("userid", userId))
    }

    fun updateToken(token: Token): Int {
        return tokenMapper.updateById(token)
    }

    fun insertToken(token: Token): Int {
        return tokenMapper.insert(token)
    }

    fun checkToken(token: String?): BaseResponse<Token> {
        if (token.isNullOrBlank()) {
            return BaseResponse.fail(Constants.ErrorCode.TOKEN_MISSING.message, Constants.ErrorCode.TOKEN_MISSING.code)
        }
        val tokenBean = tokenMapper.selectOne(QueryWrapper<Token>().eq("token", token)) ?: return BaseResponse.fail(Constants.ErrorCode.TOKEN_INVALID.message, Constants.ErrorCode.TOKEN_INVALID.code)
        if (System.currentTimeMillis() >= tokenBean.expirationTime) {
            return BaseResponse.fail(Constants.ErrorCode.TOKEN_EXPIRED.message, Constants.ErrorCode.TOKEN_EXPIRED.code)
        }
        return BaseResponse.success(tokenBean)
    }


}